'use strict';
const Controller = require('egg').Controller;
const marked = require('marked')
class PostController extends Controller {

    // 首页列表
    async index() {

        const {ctx,config} = this;

        let page = parseInt(ctx.query.page, 10) || 1;
        page = page > 0 ? page : 1;

        const limit = config.page_limit_count;

        const options = {
            skip: (page - 1) * limit,
            limit
        };

        let sort = ctx.query.sort;

        let oSort;

        if(sort == "newest"){
            oSort = {
                time:-1
            }
        }else{
            oSort = {
                read:-1
            }
        }

        const oSearch = {
            pub:'1'
        }
        
        const posts = await this.service.post.findAll(oSearch,oSort,options);

        const all_article_count = await this.service.post.getArticleCount(oSearch);
        console.log(all_article_count)

        const pages = Math.ceil(all_article_count / limit);

        // 这里需要注意的是，给模板传的参数是一个对象,然后就可以在模板中通过对象中的 key 键来获取相应的值
        await this.ctx.render('index.ejs', {
          posts:posts,
          title: '码咯-首页',
          user: this.ctx.session.user,
          success: "",
          error: "",
          sort:sort,
          current_page: page,
          pages,
          limit_count: limit,
          base:"/"
        })
    }     

    // 搜索文章
    async searchArticle() {
        const {ctx} = this;
        let kw = ctx.query.q;
        let query = {$or: [{"title":new RegExp(kw)},{"post":new RegExp(kw)}],"pub":1}
        const posts = await this.service.post.searchArticle(query);
        // 这里需要注意的是，给模板传的参数是一个对象,然后就可以在模板中通过对象中的 key 键来获取相应的值
        await ctx.render('search.ejs', {
          posts:posts,
          title: '搜索',
          user: ctx.session.user,
          success: "",
          error: ""
        })
    }

    // 查看一个文章
    async getDetailsById() {

        const {ctx} = this;

        if (ctx.params.id.length !== 24) {
            ctx.body = "文章不存在";
            return;
        }

        const details = await this.service.post.findById(ctx.params.id);

        //阅读量自增
        await this.service.post.findAndUpdate(ctx.params.id,{$inc:{read:1}});
        
        // 这里需要注意的是，给模板传的参数是一个对象,然后就可以在模板中通过对象中的 key 键来获取相应的值

        details.post = marked(details.post)

        await ctx.render('detail.ejs', {
          details:details,
          title: details.title,
          user: ctx.session.user,
          success: "",
          error: ""
        })
    }

    //获取个人专栏文章列表
    async getArticleByUserName() {

        const {ctx,config} = this;

        let page = parseInt(ctx.query.page, 10) || 1;
        page = page > 0 ? page : 1;

        const limit = config.page_limit_count;

        const options = {
            skip: (page - 1) * limit,
            limit
        };

        let sort = ctx.query.sort;

        let oSort;

        if(sort == "newest"){
            oSort = {
                time:-1
            }
        }else{
            oSort = {
                read:-1
            }
        }

        const posts = await this.service.post.findAll({name:ctx.params.name},oSort,options);

        const all_article_count = await this.service.post.getArticleCount({name:ctx.params.name});

        const pages = Math.ceil(all_article_count / limit);

        // 这里需要注意的是，给模板传的参数是一个对象,然后就可以在模板中通过对象中的 key 键来获取相应的值
        await ctx.render('my.ejs', {
          posts:posts,
          title: '个人专栏',
          user: ctx.session.user,
          success: "",
          error: "",
          current_page: page,
          pages,
        //   limit_count: limit,
          base:"/u/"+ctx.session.user.name,
          sort:sort
        })
    }

    //写文章
    async post() {
        const { ctx } = this;
        // 渲染编辑页并传参
        await ctx.render('post.ejs', {
            title: '写文章',
            user: ctx.session.user,
            success: "",
            error: "",
            type:1
        });
    }

    //编辑文章
    async edit() {
        if (!this.isLogin()) {
            return this.ctx.redirect('/login');
        }
        const { ctx } = this;

        let id = ctx.params.id

        const content = await this.service.post.findById(id);

        // 渲染编辑页并传参
        await ctx.render('edit.ejs', {
            details:content,
            posthtml:marked(content.post),
            title: '编辑文章',
            user: ctx.session.user,
            success: "",
            error: "",
            type:1
        });
    }

    //发布文章
    async save() {

        if (!this.isLogin()) {
            return this.ctx.redirect('/login');
        }

        var ctx = this.ctx;

        var body = ctx.request.body

        let id = ctx.params.id

        let date = new Date();

        //存储各种时间格式，方便以后扩展
        let time = {
            date: date,
            year : date.getFullYear(),
            month : date.getFullYear() + "-" + (date.getMonth() + 1),
            day : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
            minute : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + 
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) 
        }

        const createRule = {
            title: 'string',
            category: 'string',
            pub:'string',
            post:'string'
        }
        // ctx.validate(createRule, body)

        if(body.pub == "on"){
            body.pub = 0
        }else{
            body.pub = 1
        }

        let param = {

            name: ctx.session.user.name,

            time: time,
        
            //被喜欢量
            like: 0,
        
            //阅读量
            read: 0,
        
            //留言
            comments:[]

        };

        await this.service.post.create(Object.assign(param,body));

        ctx.redirect(`/`)

        console.log("发布成功")
        
    }

    //更新文章
    async update() {

        if (!this.isLogin()) {
            return this.ctx.redirect('/login');
        }

        var ctx = this.ctx;

        let id = ctx.params.id

        var body = ctx.request.body

        let date = new Date();

        //存储各种时间格式，方便以后扩展
        let time = {
            date: date,
            year : date.getFullYear(),
            month : date.getFullYear() + "-" + (date.getMonth() + 1),
            day : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate(),
            minute : date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + 
            date.getHours() + ":" + (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) 
        }

        const createRule = {
            title: 'string',
            category: 'string',
            pub:'string',
            post:'string'
        }
        // ctx.validate(createRule, body)

        if(body.pub == "on"){
            body.pub = 0
        }else{
            body.pub = 1
        }

        await this.service.post.findAndUpdate(id,body);

        console.log("修改成功")

        ctx.redirect(`/detail/${id}`)
        
    }

    // 删除一篇文章
    async remove() {
        const {ctx,service} = this;
        const id = ctx.params.id;
        await service.post.findAndRemove(id);
        ctx.redirect(`/u/${ctx.session.user.name}`);
    }

    //检查是否登录
    isLogin(){
        if (!this.ctx.session.user) {
            return false
        }else{
            return true
        }
    }
}
module.exports = PostController;
